package com.water.camera.util;

import static android.text.Spanned.SPAN_EXCLUSIVE_INCLUSIVE;
import static com.plata.base.aclr.utils.NetworkUtils.close;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.TextView;

import com.plata.base.aclr.utils.SPHelper;
import com.water.camera.App;
import com.water.camera.BuildConfig;
import com.water.camera.bean.EditItem;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class Utils {

    public static int getStatusBarHeight(Context c) {
        int result = 0;
        Resources resources = c.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = resources.getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static int getLayoutByName(String aString) {
        int resId = App.getApp().getResources().getIdentifier(aString, "layout", App.getApp().getPackageName());
        return resId;
    }

    public static int dp2Px(Context context, float dipValue) {
        final float scale = context.getResources()
                .getDisplayMetrics().density;
        int pxValue = (int) (dipValue * scale + 0.5f);

        return pxValue;
    }

    public static int getScreenWidth() {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) App.getApp()
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getMetrics(dm);
        return dm.widthPixels;
    }

    public static int getScreenHeight() {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) App.getApp()
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getMetrics(dm);
        return dm.heightPixels;
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / (scale <= 0 ? 1 : scale) + 0.5f);
    }

    public static void freeWeb(WebView wb) {
        try {
            if (wb == null) {
                return;
            }
            if (wb.getParent() instanceof ViewGroup) {
                ((ViewGroup) wb.getParent()).removeView(wb);
            }
            wb.setWebChromeClient(null);
            wb.setWebViewClient(null);
            wb.removeAllViews();
            wb.destroy();
        } catch (Throwable e) {

        }
    }

    public static void setClickableText(TextView tv, String str) {
        int color = isTwo() ? 0xff00B386 : 0xff38BFC6;
        SpannableString ss = new SpannableString(str);
        MyClickableSpan s = new MyClickableSpan(tv.getContext(), Constant.AGREE, color);
        int i1 = str.indexOf("《");
        int e1 = str.indexOf("》") + 1;
        ss.setSpan(s, i1, e1, SPAN_EXCLUSIVE_INCLUSIVE);
        int i2 = str.indexOf("《", i1 + 1);
        int e2 = str.indexOf("》", e1) + 1;
        ss.setSpan(new MyClickableSpan(tv.getContext(), Constant.PRIVACY, color), i2, e2, SPAN_EXCLUSIVE_INCLUSIVE);
        tv.setLineSpacing(0, 1.2f);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setHighlightColor(tv.getContext().getResources().getColor(android.R.color.transparent));
        tv.setText(ss);
    }

    public static void setClickableText(TextView tv, String str, String url) {
        int color = isTwo() ? 0xff00B386 : 0xff38BFC6;
        SpannableString ss = new SpannableString(str);
        MyClickableSpan s = new MyClickableSpan(tv.getContext(), url, color);
        int i1 = str.indexOf("《");
        int e1 = str.indexOf("》") + 1;
        ss.setSpan(s, i1, e1, SPAN_EXCLUSIVE_INCLUSIVE);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setHighlightColor(tv.getContext().getResources().getColor(android.R.color.transparent));
        tv.setText(ss);
    }

    public final static boolean isTwo() {
        return BuildConfig.APPLICATION_ID.endsWith(".me");
    }

    public static String getDay(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String day = sdf.format(d);
        return day;
    }

    public static String getDay2(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String day = sdf.format(d);
        return day;
    }

    public static String getDay4(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm yyyy-MM-dd");
        String day = sdf.format(d);
        return day;
    }

    public static String getDay3(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        String day = sdf.format(d);
        return day;
    }

    public static String getDay5(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String day = sdf.format(d);
        return day;
    }

    public static String getDay1(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        String day = sdf.format(d);
        return day;
    }

    public static String getDay6(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        String day = sdf.format(d);
        return day;
    }

    public static String getHour(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String day = sdf.format(d);
        return day;
    }

    public static String getHour2(long time) {
        Date d = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String day = sdf.format(d);
        return day;
    }

    public static long date2Ms(String _data) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = format.parse(_data);
            return date.getTime();
        } catch (Exception e) {
            return 0;
        }
    }

    public static long date2Ms2(String _data) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date date = format.parse(_data);
            return date.getTime();
        } catch (Exception e) {
            return 0;
        }
    }

    public static String dateToWeek(long time) {
        return dateToWeek(time, 0);
    }

    public static String dateToWeek(long time, int type) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        cal.setTimeInMillis(time);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0) w = 0;
        String s = weekDays[w];
        if (type == 0) {
            return s;
        } else {
            return s.replace("星期", "周");
        }
    }

    public static String getValue(float value) {
        DecimalFormat decimalFormat = new DecimalFormat("#0.0"); // 设置格式化模式为保留两位小数
        String result = decimalFormat.format(value);
        return result;
    }

    public final static void copy(String str) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) App.getApp().getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", str);
// 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }

    public static boolean saveImageTo(Bitmap bmp, String path) {
        //获取文件
        File file = new File(path);
        file.getParentFile().mkdirs();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            Log.e("picture", "保存成功");
            return true;
        } catch (Exception e) {
            Log.e("bitmaperr", e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                bmp.recycle();
            } catch (Exception e) {
                Log.e("bitmaperr", e.getMessage());
                e.printStackTrace();
            }
        }
        return false;
    }

    public static void setText(TextView tv, String key, boolean isDefault, View... group) {
        setText(tv, key, null, isDefault, group);
    }

    public static void setText(TextView tv, String key, String str, boolean isDefault, View... group) {
        tv.setMaxLines(1);
        if (group != null && group.length > 0) {
            group[0].setTag(key);
            if (tv != group[0]) {
                tv.setTag(key + "_value");
            }
        } else {
            tv.setTag(key);
        }
        String s = null;
        if (!isDefault) {
            if (key.contains("jingwei")) {
                s = new EditItem(key).getStringPoint();
            } else {
                s = SPHelper.getInstance(App.getApp()).getString(key, null);
            }
        }
        if (TextUtils.isEmpty(s)) {
            if (TextUtils.isEmpty(str)) {
                s = tv.getText().toString();
                if (TextUtils.isEmpty(s)) {
                    s = "点击编辑本条内容";
                }
            } else {
                s = str;
            }
        }
        tv.setText(s);
    }

    public static boolean isInstalled(String pkg) {
        return getLauncherByPkg(App.getApp(), pkg) != null;
    }

    public static Intent getLauncherByPkg(Context context, String appName) {
        try {
            return context.getPackageManager().getLaunchIntentForPackage(appName);
        } catch (Throwable e) {
            return null;
        }
    }

    public static Bitmap convertViewToBitmap(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        view.draw(new Canvas(bitmap));
        return bitmap;
    }

    public static Bitmap convertViewToBitmap2(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    public static Bitmap convertViewToBitmap(View view, int w, int h) {
        view.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    public static Bitmap convertViewToBitmap(View view, int w) {
        view.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    public static boolean isSameDate(long a, long b) {
        return a / (24 * 60 * 60 * 1000L) == b / (24 * 60 * 60 * 1000L);
    }

    public static boolean isVideoByPath(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return false;
        }
        String localFilePath = filePath.trim();
        return localFilePath.toLowerCase(Locale.ENGLISH).endsWith(".mp4")
                || localFilePath.toLowerCase(Locale.ENGLISH).endsWith(".3gp")
                || localFilePath.toLowerCase(Locale.ENGLISH).endsWith(".3g2")
                || localFilePath.toLowerCase(Locale.ENGLISH).endsWith(".mkv")
                || localFilePath.toLowerCase(Locale.ENGLISH).endsWith(".mov")
                || localFilePath.toLowerCase(Locale.ENGLISH).endsWith(".m4v");
    }

    public static void copy(String src, String dst, boolean delete) {
        FileInputStream in = null;
        FileOutputStream out = null;
        boolean success = false;
        try {
            in = new FileInputStream(src);
            success = copy(in, dst);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            close(in);
            close(out);
            if (success && delete) {
                deleteFile(new File(src));
            }
        }
    }

    public static boolean copy(InputStream input, String dst) {
        BufferedInputStream in = null;
        FileOutputStream out = null;
        try {
            if (input instanceof BufferedInputStream) {
                in = (BufferedInputStream) input;
            } else {
                in = new BufferedInputStream(input);
            }
            new File(dst).getParentFile().mkdirs();
            out = new FileOutputStream(dst);
            byte[] buf = new byte[1024];
            int len;
            while (true) {
                len = in.read(buf);
                if (len <= 0) {
                    break;
                }
                out.write(buf, 0, len);
            }
            return true;
        } catch (Throwable e) {
            e.printStackTrace();
            return false;
        } finally {
            close(in);
            close(input);
            close(out);
        }
    }

    public static void deleteFile(File file) {
        if (!file.exists()) {
            return;
        }
        File tmp = new File(file.getAbsolutePath() + "_bk");
        file.renameTo(tmp);
        if (tmp.isFile()) {
            deleteOneFile(tmp);
        } else {
            deleteDirectory(tmp);
        }
    }

    private static void deleteOneFile(File file) {
        file.delete();
    }

    //删除文件夹
    private static void deleteDirectory(File folder) {
        if (folder.exists()) {
            File[] files = folder.listFiles();
            if (files == null) {
                return;
            }
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                } else {
                    files[i].delete();
                }
            }
        }
        folder.delete();
    }

    public static final List<String> PATTERN = Arrays.asList(new String[]{"%.6f,%.6f", "%.4f,%.4f", "%.6f°N,%.6f°E", "%.4f°N,%.4f°E", "%3$d°%4$.6f',%5$d°%6$.6f'", "%3$d°%4$.6f'N,%5$d°%6$.6f'E", "%3$d°%7$d'%8$.6f\",%5$d°%9$d'%10$.6f\"", "%3$d°%7$d'%8$.6f\"N,%5$d°%9$d'%10$.6f\"E", "北纬%3$d°%7$d'%11$d\",东经%5$d°%9$d'%12$d\"", "北纬%3$d°%4$.2f',东经%5$d°%6$.2f'"});

    public final static String currentPatternContent(double lat, double lng, String pattern) {
        double d = 60;
        String format = String.format(Locale.CHINA, pattern, Arrays.copyOf(new Object[]{Double.valueOf(lat), Double.valueOf(lng), Double.valueOf(lat).intValue(), Double.valueOf((lat * d) % d), Double.valueOf(lng).intValue(), Double.valueOf((lng * d) % d), Integer.valueOf((int) ((lat * d) % d)), Double.valueOf(((lat * d) * d) % d), Integer.valueOf((int) ((lng * d) % d)), Double.valueOf(((lng * d) * d) % d), Integer.valueOf((int) (((lat * d) * d) % d)), Integer.valueOf((int) (((lng * d) * d) % d))}, 12));
        return format;
    }
}
